package com.sumer.psychology.comment.application.query;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.sumer.psychology.comment.domain.model.CommentType;
import com.sumer.psychology.common.persistence.mongodb.AbstractMongoRepository;

/**
 * 评论查询
 * <p/>
 * User: zhenguang.zhu
 * Date: 2014/10/28
 * Time: 9:20
 */
public class CommentQueryApplicationService extends AbstractMongoRepository {
    /**
     * 查询一个宿主下的评论树
     *
     * @param hostId      host id
     * @param commentType comment type
     * @return json
     */
    public String findByHost(String hostId, CommentType commentType, int countPerPage, int offset) {
        DBCollection dbCollection = db().getCollection("sumer_" + commentType.toString().toLowerCase() + "_comment");

        DBCursor results = dbCollection
                .find(new BasicDBObject("host", hostId))
                .sort(new BasicDBObject("createTime", -1))
                .skip(offset)
                .limit(countPerPage);

        return serializeWithTotalCount(
                commentCount(dbCollection, hostId),
                results);
    }

    private long commentCount(DBCollection dbCollection, String hostId) {
        DBCursor allResults = dbCollection.find(new BasicDBObject("host", hostId));
        return allResults.count();
    }

    @Override
    protected String dbName() {
        return null;
    }
}
